/**
 * @fileOverview
 * @author iNahoo
 * @since 2022/3/2.
 */

const parseCSV = require('csv-parser');
const { ATTR_ID_MAP, generateCSV } = require("./common");
const { createReadStream } = require('fs');
const { resolve } = require('path');

const ORIGIN = resolve(__dirname, '../origin/素材速查.csv');
const OUTPUT_MATERIAL = resolve(__dirname, '../src/data/素材列表_std.csv');
const OUTPUT_CATEGORY = resolve(__dirname, '../src/data/分类列表_std.csv');

const table = [];

const categoryDict = {
  list: [],
  indexMap: {},

  add(v) {
    if (this.indexMap[v]) {
      return;
    }

    this.indexMap[v] = this.list.length;
    this.list.push(v);
  }
}


/**
 * 获取原始数据
 * @return {Promise}
 */
async function getOriginTable() {
  let id = 1;

  return new Promise((r, j) => {
    createReadStream(ORIGIN).pipe(parseCSV({}))
      .on('data', (data) => {
        Object.keys(data).forEach(key => {
          data[key] = data[key].trim();
        });

        data['metarialId'] = id++;
        table.push(data);
      })
      .on('end', () => {
        r(table);
      })
      .on('error', err => {
        j(err);
      })
  });
}

function standardMaterial() {
  const keyList = '1234'.split('').map(v => `类别${v}`);
  table.forEach((r, i) => {
    const c = [];
    keyList.forEach(key => {
      if (r[key]) {
        c.push(r[key]);
        categoryDict.add(r[key]);
      }
    });

    r.id = i;
    r.mainAttrId = ATTR_ID_MAP[r['固定成分属性']];
    r.mainAttrName = ATTR_ID_MAP[r.mainAttrId];
    r.categories = c.join('|');
  });
}

// 输出
function outputCategory() {
  generateCSV(
    [
      ['ID', 'i'],
      ['类型', 'name']
    ],
    categoryDict.list.map((name, i) => ({
      i,
      name
    })),
    OUTPUT_CATEGORY
  )
}

// 输出
function outputMaterial() {
  generateCSV(
    [
      ['ID', 'id'],
      ['素材名'],
      ['主属性', 'mainAttrName'],
      ['类型', 'categories'],
      ['mainAttrId'],
    ],
    table,
    OUTPUT_MATERIAL
  )
}

(async function main() {
  await getOriginTable();
  standardMaterial();
  outputCategory();
  outputMaterial();
})()
